package com.yuerlive.rainbow.rx;


import com.yuerlive.rainbow.base.BasePresenterImpl;
import com.yuerlive.rainbow.common.ActivityStack;
import com.yuerlive.rainbow.entity.BaseData;
import com.yuerlive.rainbow.utils.L;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by zhanghao on 2017/4/22.
 */

public abstract class RxObserver<T> implements Observer<T> {
    private static final String TAG = "RxObserver";

    private BasePresenterImpl presenter;


    public RxObserver(BasePresenterImpl presenter) {
        this.presenter = presenter;
    }

    @Override
    public void onSubscribe(Disposable d) {
        presenter.subscribe(d);
        L.e(TAG, this.presenter.getClass().getSimpleName());
    }

    @Override
    public void onError(Throwable t) {
        L.e(TAG, t.getMessage());
        t.printStackTrace();
        onFail(RxException.getErrorMessage(t));
    }

    @Override
    public void onComplete() {
    }

    @Override
    public void onNext(T t) {
        if (t instanceof BaseData) {
            BaseData base = (BaseData) t;
            if (base.getCode() == -4) {
                //登录失效
                ActivityStack.getTopActivity().showLogoutDialog();
                return;
            }
        }
        onSuccess(t);
    }

    protected abstract void onSuccess(T t);

    protected abstract void onFail(String message);


}
